package org.skydiveapp2;

import org.skydiveapp2.ui.InterfaceManager;
import org.skydiveapplibrary.util.RigReminderManager;

import android.app.Fragment;
import android.app.Activity;
import android.app.FragmentManager.OnBackStackChangedListener;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;

public class MainActivity extends Activity	implements OnBackStackChangedListener, 
													   LogEntryListFragment.onLogEntryEditRequestListener,
													   LogEntryEditFragment.onLogEntryEditStatusChangedListener
{
	private int selectedTab = 0;
    private boolean isDualDisplay;
    private Bundle requestedLogEntryEditArgs;
    
    private static final int LOG_ENTRY_EDIT_REPLY_CLOSED = 10;
    private static final int LOG_ENTRY_EDIT_REPLY_UPDATABLE = 20;
    
    private static final int REQUEST_LOG_ENTRY_EDIT = 10; 
    
	// listeners
	private OnClickListener tabListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			changeTab(view);
		}
	};
	
	@Override 
	public void onCreate(Bundle savedInstanceState)
	{ 
		super.onCreate(savedInstanceState);
		
		// show main view
		setContentView(R.layout.main);
		
		int savedSelectedTab = 0;
		if (savedInstanceState != null)
			savedSelectedTab = savedInstanceState.getInt("SelectedTab");
		
		// if the left frame is present the tablet view must be in use
		View logEntryLeftView = findViewById(R.id.leftFrame);
		isDualDisplay = (logEntryLeftView != null);
		
		ImageButton LogEntriesTabButton = (ImageButton) findViewById(R.id.LogEntriesTabButton);
		LogEntriesTabButton.setOnClickListener(tabListener);
		LogEntriesTabButton.setVisibility(isDualDisplay ? View.GONE : View.VISIBLE);
		
		ImageButton summaryTabButton = (ImageButton) findViewById(R.id.SummaryTabButton);
		summaryTabButton.setOnClickListener(tabListener);
		
		ImageButton gearTabButton = (ImageButton) findViewById(R.id.GearTabButton);
		gearTabButton.setOnClickListener(tabListener);
		
		ImageButton moreTabButton = (ImageButton) findViewById(R.id.MoreTabButton);
		moreTabButton.setOnClickListener(tabListener);
		
		if (isDualDisplay) //TABLET VIEW
		{
			InterfaceManager.getInstance().replaceFragment(getFragmentManager(), 
					InterfaceManager.FRAME_LEFT,
                    getLogEntryListFragment(),
                    Constants.TAG_LOG_ENTRY_LIST, false);
			
			
			if (savedSelectedTab != 0 && savedSelectedTab != R.id.LogEntriesTabButton)
				changeTab(findViewById(savedSelectedTab));
			else
				changeTab(findViewById(R.id.SummaryTabButton));
			
			InterfaceManager.getInstance().configureTabletUI(this);
			
			getFragmentManager().addOnBackStackChangedListener(this);
	    }
		else //PHONE VIEW
		{
			if (savedSelectedTab != 0 && savedSelectedTab != R.id.LogEntriesTabButton)
			{
				getLogEntryListFragment();
				changeTab(findViewById(savedSelectedTab));
			}
			else
				changeTab(findViewById(R.id.LogEntriesTabButton));
			
			InterfaceManager.getInstance().configurePhoneUI(this);
			checkIsLogEntryEditFragmentOpen();
		}
		
		// check rig reminders
		RigReminderManager.getInstance().showRigReminderAlert(this);
	}
	
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("SelectedTab", selectedTab);
    }
	
	private void changeTab(View view)
	{
		Fragment fragment = null;
		String fragTag = null;
		
		if (view.getId() == selectedTab)
				return;
		
		if (selectedTab != 0)
			this.findViewById(selectedTab).setSelected(false);
		
		view.setSelected(true);
		selectedTab = view.getId();
		
		switch (view.getId())
		{
		case R.id.LogEntriesTabButton:
			fragment = getLogEntryListFragment();
			fragTag = Constants.TAG_LOG_ENTRY_LIST;
			break;
		case R.id.SummaryTabButton:
			fragment = new SummaryActivity();
			fragTag = Constants.TAG_SUMMARY;
			break;
		case R.id.GearTabButton:
			fragment = new GearListFragment();
			fragTag = Constants.TAG_GEAR_LIST;
			break;
		case R.id.MoreTabButton:
			fragment = new MoreActivity();
			fragTag = Constants.TAG_MORE;
			break;
		}
		
		InterfaceManager.getInstance().replaceFragment(getFragmentManager(), 
				InterfaceManager.FRAME_RIGHT_SUB,
				fragment,
				fragTag,
				false);
	}

	@Override
	public void onBackStackChanged()
	{
		if (getFragmentManager().getBackStackEntryCount() == 0)
		{
			switch (selectedTab)
			{
			case R.id.SummaryTabButton:
				InterfaceManager.getInstance().setSubtitleText(this, R.string.main_summary_tab_label);
				((SummaryActivity) getFragmentManager().findFragmentByTag(Constants.TAG_SUMMARY)).loadData();
				break;
			case R.id.GearTabButton:
				InterfaceManager.getInstance().setSubtitleText(this, R.string.main_gear_tab_label);
				break;
			case R.id.MoreTabButton:
				InterfaceManager.getInstance().setSubtitleText(this, R.string.main_more_tab_label);
				break;
			}
		}
	}
	
	@Override
	public void onBackPressed()
	{
		LogEntryEditFragment logEntryEditFragment = (LogEntryEditFragment) getFragmentManager().
				findFragmentByTag(Constants.TAG_LOG_ENTRY_EDIT);
		
		if (logEntryEditFragment != null)
		{
			logEntryEditFragment.requestClose();
		}
		else
		{
			finish();
		}
		
	}
	
	// The LogEntryListFragment needs to be moved from one container to another.
	// A remove call must be processed before it can be added to another container.
	private Fragment getLogEntryListFragment()
	{
		Fragment logEntryListFragment = getFragmentManager().
				findFragmentByTag(Constants.TAG_LOG_ENTRY_LIST);
		if (logEntryListFragment != null)
		{
			FragmentTransaction ft = getFragmentManager().beginTransaction();
			ft.remove(logEntryListFragment);
			ft.commit();
			getFragmentManager().executePendingTransactions();
		}
		else
			logEntryListFragment = new LogEntryListFragment();
		
		return logEntryListFragment;
	}

	@Override
	public void onLogEntryEditRequest(Bundle args) {
		
		requestedLogEntryEditArgs = args;
		
		if (isDualDisplay)
		{
			launchLogEntryEditFragment();
		}
		else
		{
			launchLogEntryEditActivity();
		}

	}
	
	private void launchLogEntryEditFragment()
	{
		LogEntryListFragment logEntryListFragment = (LogEntryListFragment) getFragmentManager()
				.findFragmentByTag(Constants.TAG_LOG_ENTRY_LIST);
		LogEntryEditFragment logEntryEditFragment = (LogEntryEditFragment) getFragmentManager()
				.findFragmentByTag(Constants.TAG_LOG_ENTRY_EDIT);
		
		if (logEntryEditFragment != null)
		{
			if (logEntryEditFragment.requestUpdate())
			{
				logEntryEditFragment.updateContent(requestedLogEntryEditArgs);
				
				if (requestedLogEntryEditArgs.containsKey(Constants.EXTRA_LOG_ENTRY_ID))
					logEntryListFragment.highlightRow(requestedLogEntryEditArgs.getInt(Constants.EXTRA_LOG_ENTRY_ID));
				else
					logEntryListFragment.refreshListView();
			}
		}
		else
		{
			InterfaceManager.getInstance().replaceFragment(getFragmentManager(),
					InterfaceManager.FRAME_RIGHT,
				LogEntryEditFragment.newInstance(requestedLogEntryEditArgs),
				Constants.TAG_LOG_ENTRY_EDIT, true,
				R.animator.fadein, R.animator.fadeout);
			
//			if (isDualDisplay)
//			{
			if (requestedLogEntryEditArgs.containsKey(Constants.EXTRA_LOG_ENTRY_ID))
				logEntryListFragment.highlightRow(requestedLogEntryEditArgs.getInt(Constants.EXTRA_LOG_ENTRY_ID));
			else
				logEntryListFragment.refreshListView();
//			}
		}
	}
	
	private void launchLogEntryEditActivity()
	{
		Intent intent = new Intent(this, LogEntryEditActivity.class);
		intent.putExtras(requestedLogEntryEditArgs);
		startActivityForResult(intent, REQUEST_LOG_ENTRY_EDIT);
	}

	@Override
	public void onLogEntryEditStatusChanged(int response) {

		LogEntryListFragment logEntryListFragment = (LogEntryListFragment) getFragmentManager()
				.findFragmentByTag(Constants.TAG_LOG_ENTRY_LIST);
		
		LogEntryEditFragment logEntryEditFragment = (LogEntryEditFragment) getFragmentManager()
				.findFragmentByTag(Constants.TAG_LOG_ENTRY_EDIT);
		
		if (response == LOG_ENTRY_EDIT_REPLY_CLOSED) //LogEntryEdit closed
		{		
			logEntryListFragment.refreshListView();

		}
		else if (response == LOG_ENTRY_EDIT_REPLY_UPDATABLE) //LogEntryEdit ready for action
		{
			if (logEntryEditFragment != null)
			{
				logEntryEditFragment.updateContent(requestedLogEntryEditArgs);
			}
			else
			{
				InterfaceManager.getInstance().replaceFragment(getFragmentManager(),
					InterfaceManager.FRAME_RIGHT,
					LogEntryEditFragment.newInstance(requestedLogEntryEditArgs),
					Constants.TAG_LOG_ENTRY_EDIT, true,
					R.animator.fadein, R.animator.fadeout);
			}
			
			if (isDualDisplay)
			{
				if (requestedLogEntryEditArgs.containsKey(Constants.EXTRA_LOG_ENTRY_ID))
					logEntryListFragment.highlightRow(requestedLogEntryEditArgs.getInt(Constants.EXTRA_LOG_ENTRY_ID));
				else
					logEntryListFragment.refreshListView();
			}
		}	
	}
	
	// Called when MainActivity is launched to see if there is a LogEntryEditFragment open
	// If so it will be closed and launched as an activity.
	private void checkIsLogEntryEditFragmentOpen()
	{
		LogEntryEditFragment logEntryEditFragment = (LogEntryEditFragment) getFragmentManager()
				.findFragmentByTag(Constants.TAG_LOG_ENTRY_EDIT);
		
		if (logEntryEditFragment != null)
		{
			requestedLogEntryEditArgs = logEntryEditFragment.configureBundle(new Bundle());
			getFragmentManager().popBackStack();
			getFragmentManager().executePendingTransactions();
			
			launchLogEntryEditActivity();
		}
	}
	
	public void updateLogEntryListView()
	{
		LogEntryListFragment logEntryListFragment = (LogEntryListFragment) getFragmentManager()
				.findFragmentByTag(Constants.TAG_LOG_ENTRY_LIST);
		
		if (logEntryListFragment != null)
			logEntryListFragment.refreshListView();
	}
	
	// Called when the LogEntryEditActivity detects its running while in a tablet view.
	// This launches the same window as a fragment.
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        if (requestCode == REQUEST_LOG_ENTRY_EDIT && resultCode == RESULT_OK)
        {
            requestedLogEntryEditArgs = intent.getExtras();
            launchLogEntryEditFragment();
        }
        else
        {
        	Log.e("skydive", "RESULT!!!");
        	super.onActivityResult(requestCode, resultCode, intent);
        }
    }
}